//
//  MainVC.swift
//  mmda
//
//  Created by 李陆涛 on 2018/4/16.
//  Copyright © 2018年 mmda. All rights reserved.
//

import UIKit
import SideMenu

class MainVC: BaseVC {
    
    @IBOutlet weak var tagView: UIView!
    @IBOutlet weak var tagViewLeading: NSLayoutConstraint!
    
    @IBOutlet weak var blogBtn: UIButton!
    @IBOutlet weak var userBtn: UIButton!
    
    @IBOutlet weak var mapview: BMKMapView!
    private var userlocation: BMKUserLocation!
    
    
    
    @IBOutlet weak var refreshBtn: UIButton!
    
    var viewModel: MainVCViewModel!
    
    var locationManager:BMKLocationManager!
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
        setupData()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        
        super.viewDidAppear(animated)
        
        DispatchQueue.once(token: "update") {
            [weak self] in
            guard let `self` = self else { return }
            
            self.updateApp()
        }
    }
    
//    override func viewWillAppear(_ animated: Bool) {
//        super.viewWillAppear(animated)
//
//
//        viewModel.forceReload(mapview.centerCoordinate)
//    }
//
//    override func viewWillDisappear(_ animated: Bool) {
//        super.viewWillDisappear(animated)
//
//        mapview.viewWillDisappear()
//        mapview.delegate = nil
//    }
    
    func setupUI() {
        
        self.view.backgroundColor = UIColor.black
        let meunNav = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "SideMenu") as! UISideMenuNavigationController
        
        SideMenuManager.default.menuLeftNavigationController = meunNav
        SideMenuManager.default.menuFadeStatusBar = false
        
        let width = CGFloat(kScreenWidth) * 2 / 3
        
        SideMenuManager.default.menuWidth = width
        
        NotificationCenter.default.addObserver(self, selector: #selector(backMapNotifation(_:)), name: kBackMapReloadNotifationName, object: nil)
        
        mapview.showMapScaleBar = true
        mapview.mapScaleBarPosition = CGPoint(x: CGFloat(kScreenWidth) - 96, y: 16)
        
        mapview.showMapPoi = true
//        mapview.isRotateEnabled = false
        mapview.isOverlookEnabled = true
        mapview.isBuildingsEnabled = true
//        mapview.compassPosition = CGPoint(x: 16, y: 16)
        
        mapview.mapType = .standard
        
        mapview.showsUserLocation = true
        
        mapview.gesturesEnabled = true
        mapview.userTrackingMode = BMKUserTrackingModeHeading
        
        mapview.viewWillAppear()
        mapview.delegate = self
        
        originMapCenter()
        
        locationManager = BMKLocationManager()
        locationManager.delegate = self
        locationManager.coordinateType = .BMK09LL
        locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters
        locationManager.pausesLocationUpdatesAutomatically = false
        locationManager.locationTimeout = 10
        
        locationManager.startUpdatingHeading()
        locationManager.startUpdatingLocation()
        
        userlocation = BMKUserLocation()
        
        
    }
    
    func setupData() {
        
        self.viewModel = MainVCViewModel()
        
        self.viewModel.addMapData = {
            [weak self] annArray in
            guard let `self` = self else { return }
            
            self.mapview.addAnnotations(annArray)
        }
        
        self.viewModel.refreshStatusDidChange = {
            [weak self] refreshing in
            guard let `self` = self else { return }
            
            if refreshing {
                
                self.startRefreshAnimation()
            } else {
                
                self.stopRefreshAnimation()
            }
        }
        
        self.viewModel.removeMapData = {
            [weak self] in
            guard let `self` = self else { return }
            
            self.mapview.removeAnnotations(self.mapview.annotations)

        }
    }
    
    private func updateApp() {
        
        guard let netversion = AppManager.share.appModel?.app_ios?.version else { return }
        let appversion = kVersion as! String
        
        if appversion.compare(netversion) != .orderedAscending {
            
            return
        }
        
        var forceupdate = false
        
        if let upgradeversion = AppManager.share.appModel?.app_ios?.version_upgrade,appversion.compare(upgradeversion) == .orderedAscending {
            
            forceupdate = true
        }
        
        let msg = "\(AppManager.share.appModel?.app_ios?.version_upgrade_content ?? "当前版本 \(appversion)")\n是否更新到版本\(netversion)"
        
        let alertVC = UIAlertController(title: "发现新版本", message: msg, preferredStyle: .alert)
        
        alertVC.addAction(UIAlertAction(title: "去更新", style: UIAlertActionStyle.default, handler: {
            
            [weak self] _ in
            guard let `self` = self else { return }
            
            UIApplication.shared.openURL(URL(string: "https://itunes.apple.com/cn/app/id1288978316")!)
            
            if forceupdate {
                
                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1.0, execute: {
                    
                    self.present(alertVC, animated: true, completion: nil)
                })
            }
            
        }))
        
        if !forceupdate {
            
            alertVC.addAction(UIAlertAction(title: "取消", style: UIAlertActionStyle.cancel, handler: nil))
        }
        
        self.present(alertVC, animated: true, completion: nil)
    }
    
    private func originMapCenter() {
        
        mapview.setCenter(AppManager.share.cLocation?.coordinate ?? mapview.centerCoordinate, animated: true)
        mapview.zoomLevel = 17
        mapview.rotation = 0
    }
    
    @objc func backMapNotifation(_ noti:Notification) {
        
        guard let blog = noti.userInfo?[kNotifationNameObj] as? Blog else {
            viewModel.forceReload(mapview.centerCoordinate)
            
            return
        }
        
        if viewModel.showType != ShowType.blog {
            
            showBlogAction(blogBtn)
        }
        
        guard let lat = blog.latitude,let lng = blog.longitude else { return }
        
        let loc = CLLocationCoordinate2DMake(lat, lng)
        
        mapview.setCenter(loc, animated: true)
        viewModel.forceReload(loc)
    }
    
    //    按钮点击事件
    
    
    @IBAction func showAccount(_ sender: UIBarButtonItem) {
        
        if self.hasLogin() {
            
            let leftVC = SideMenuManager.default.menuLeftNavigationController!
            
            self.present(leftVC, animated: true, completion: nil)
        }
    }
    @IBAction func showAll(_ sender: UIBarButtonItem) {
        
        if self.hasLogin() {
            let sendPhotoVC = ShowAllVC()
            
            self.navigationController?.pushViewController(sendPhotoVC, animated: true)
        }
    }
    
    @IBAction func showBlogAction(_ sender: UIButton) {
        
        self.viewModel.showType = ShowType.blog
        makeTagViewAnimation()
    }
    
    @IBAction func showUserAction(_ sender: UIButton) {
        
        self.viewModel.showType = ShowType.user
        makeTagViewAnimation()
    }
    
    @IBAction func showUserLocationAction(_ sender: Any) {
        
        
        originMapCenter()
    }
    
    @IBAction func refreshAction(_ sender: Any) {
        
        viewModel.forceReload(mapview.centerCoordinate)
    }
    @IBAction func addAction(_ sender: Any) {

        if !hasLogin() {

            return
        }
        
        if !AppManager.share.hasAgree {
            
            let webVC = WebVC()
            webVC.url = AppManager.share.appModel?.app_agreement?.url
            webVC.pageType = 1
            
            self.present(webVC, animated: true, completion: nil)
            
            webVC.agreeBlock = {
                
                [weak self] in
                guard let `self` = self else { return }
                
                AppManager.share.hasAgree = true
                
                DispatchQueue.main.after(0.25, block: {

                    self.addAction(sender)
                })
            }
            
            return
        }
        
        
        PhotoAlertVC.alert(type: .all, maxCount: 9, vc: self) {
            
            [weak self] modelArray,type in
            guard let `self` = self else { return }
            
            DispatchQueue.main.after(0.25, block: {
                
                let sendVC = SendPhotoVC(models: modelArray,type: type)
                
                self.navigationController?.pushViewController(sendVC, animated: true)
            })
        }
    }
    
    @IBAction func biggerMapAction(_ sender: Any) {
        
        mapview.zoomIn();
    }
    @IBAction func smallerMapAction(_ sender: Any) {
        
        mapview.zoomOut()
    }

    //    动画
    func makeTagViewAnimation() {
        
        let constant = viewModel.showType == ShowType.user ? userBtn.frame.origin.x - blogBtn.frame.origin.x : 0
        
        self.tagViewLeading.constant = constant
        
        UIView.animate(withDuration: 0.25) {
            [weak self] in
            guard let `self` = self else { return }
            self.view.layoutIfNeeded()
        }
    }
    
    func startRefreshAnimation () {
        
        stopRefreshAnimation()
        let rotateAni = CABasicAnimation(keyPath: "transform.rotation")
        rotateAni.fromValue = 0.0
        rotateAni.toValue = Double.pi * 2.0
        rotateAni.duration = 1
        rotateAni.repeatCount = MAXFLOAT
        self.refreshBtn.layer.add(rotateAni, forKey: nil)
    }
    
    func stopRefreshAnimation() {
        
        self.refreshBtn.layer.removeAllAnimations()
    }
}

// 地图代理

extension MainVC: BMKMapViewDelegate {
    
    
//    func mapViewDidFinishRendering(_ mapView: BMKMapView!) {
//
//        DispatchQueue.once(token: "reloadData") {
//
//            [weak self] in
//            guard let `self` = self else { return }
//
//            self.viewModel.forceReload(self.mapview.centerCoordinate)
//        }
//    }
    
    func mapView(_ mapView: BMKMapView!, regionDidChangeAnimated animated: Bool) {
        
        viewModel.lastLoc = mapView.centerCoordinate
    }
    
    func mapView(_ mapView: BMKMapView!, viewFor annotation: BMKAnnotation!) -> BMKAnnotationView! {
        
        if !annotation.isKind(of: Annotation.self) {
            return nil
        }
        
        var annview = mapView.dequeueReusableAnnotationView(withIdentifier: "Annotation") as? ImageAnnView
        
        if annview == nil {
            
            annview = ImageAnnView(annotation: annotation, reuseIdentifier: "Annotation")
        }
        
        annview?.setup(with: annotation as? Annotation)
        
        return annview
    }
    
    func mapView(_ mapView: BMKMapView!, didSelect view: BMKAnnotationView!) {
        
        mapView.deselectAnnotation(view.annotation, animated: false)
        
        if !hasLogin() {
            
            return
        }
        
        guard let ann = view.annotation as? Annotation else { return }
        
        if let user = ann.model as? User {
            
            let userBlogVC = BlogOrUserListVC(pageType: .auser, userid: user._id)
            
            self.navigationController?.pushViewController(userBlogVC, animated: true)
            
            return
        }
        
        if let blog = ann.model as? Blog {
            
            let detailVC = BlogDetailVC(blog)
            
            self.navigationController?.pushViewController(detailVC, animated: true)
            
            return
        }
    }
}

extension MainVC : BMKLocationManagerDelegate {
    
    func bmkLocationManager(_ manager: BMKLocationManager, didUpdate heading: CLHeading?) {
        
        guard let heading = heading else { return }
        

        userlocation.heading = heading
        
        mapview.updateLocationData(userlocation)
    }
    
    func bmkLocationManager(_ manager: BMKLocationManager, didUpdate location: BMKLocation?, orError error: Error?) {
        
        guard let location = location else { return }
        
        userlocation.location = location.location
        AppManager.share.cLocation = location.location
        
        mapview.updateLocationData(userlocation)
        
        DispatchQueue.once(token: "reloadData") {
            
            [weak self] in
            guard let `self` = self else { return }
            
            if let center = location.location?.coordinate  {
                
                self.mapview.setCenter(center, animated: true)
            }
            
            self.viewModel.forceReload(location.location?.coordinate ?? self.mapview.centerCoordinate)
        }

    }
}



